import { defineStore } from 'pinia'
import { v4 as uuidv4 } from 'uuid'
import type { CustomClipboardItem, SharedItem } from '../types/clipboard'

export const useClipboardStore = defineStore('clipboard', {
  state: () => ({
    deviceId: localStorage.getItem('deviceId') || uuidv4(),
    history: [] as CustomClipboardItem[],
    sharedItems: [] as SharedItem[]
  }),

  actions: {
    // 初始化历史记录
    initHistory() {
      // 从 uTools DB 加载历史记录
      const docs = utools.db.allDocs('clipboard/')
      this.history = docs.map(doc => {
        const { _id, _rev, ...rest } = doc
        return {
          ...rest,
          id: _id.replace('clipboard/', ''),
          type: rest.type || 'text',
          content: rest.content || '',
          timestamp: rest.timestamp || Date.now(),
          deviceId: rest.deviceId || this.deviceId
        } as CustomClipboardItem
      })
    },

    // 添加新记录
    async addItem(item: CustomClipboardItem) {
      // 保存到 uTools DB
      await utools.db.put({
        _id: `clipboard/${item.id}`,
        ...item
      })
      
      this.history.unshift(item)
    },

    // 删除历史记录
    async removeHistoryItem(id: string) {
      await utools.db.remove(`clipboard/${id}`)
      const index = this.history.findIndex(item => item.id === id)
      if (index > -1) {
        this.history.splice(index, 1)
      }
    },

    // 获取历史记录
    getHistory() {
      return this.history
    },

    // 分享内容
    async shareItem({ 
      item,
      password,
      expiry 
    }: {
      item: CustomClipboardItem
      password?: string
      expiry: string
    }) {
      // 生成分享记录
      const shareId = uuidv4()
      const expiryTime = getExpiryTime(expiry)
      
      // 如果设置了密码，加密内容
      const content = password 
        ? await window.clipboardAPI.encrypt(item.content as string, password)
        : item.content

      // 保存分享记录
      await utools.db.put({
        _id: `share/${shareId}`,
        content,
        type: item.type,
        encrypted: !!password,
        expiry: expiryTime,
        createdAt: Date.now()
      })

      // 生成分享链接
      return `https://your-share-service.com/share/${shareId}`
    }
  }
})

// 计算过期时间
function getExpiryTime(expiry: string): number {
  const now = Date.now()
  switch (expiry) {
    case '1h': return now + 3600000
    case '24h': return now + 86400000
    case '7d': return now + 604800000
    default: return 0 // 永不过期
  }
} 